<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Db;
class Wechat extends Controller
{
	public function __construct(){

		$code=input('code');
        $website=website();
		if($code){
            //获取微信用户信息
			$userinfo = getUserInfo($code);

            //判断code是否能获取，否则重新获取
                if(!$userinfo['openid']){
                    $Wechat_url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$website['appid']."&redirect_uri=".$website['web_url']."index.php/index/user/index&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
                    $this->redirect($Wechat_url);
                }

            $where['openid']=$userinfo['openid'];
            $user=Db::name('user')->where($where)->find();
            if(!$user){
                    $data['addtime']=date('Y-m-d H:i:s',time());
                    $data['openid']=$userinfo['openid'];
                    $data['sex']=$userinfo['sex'];
                    $data['area']=$userinfo['country']."_".$userinfo['province']."_".$userinfo['city'];
                    $data['head']=$userinfo['headimgurl'];
                    $data['username']=base64_encode($userinfo['nickname']);
                    $info=Db::name('user') -> insert($data);
                    if(!$info){
                        $this->error('异常！',url('index/index'));
                    }
                    $this->redirect('login/index');
            }


            //微信用户openid 存入 SESSION
			Session::set('wechat_user',$userinfo['openid']);
		}
        parent::__construct();
        //基本设置
        
        $this->view->assign('website', $website);
        //资源目录
        $this->view->assign('Assets', Assets);
        //检测是否登陆
        $this->wechatlogin();

        //获取当前用户信息
        $openid=Session::get('wechat_user');
        $user=get_user_openid($openid);
        $user['username']=base64_decode($user['username']);//名称解密

        if(!$user['telphone']){
            	$this->redirect('login/index');
        }

        //获取最新积分
        
        $integral_json=erp_active($user['telphone']);
        $integral_array=json_decode($integral_json,true);
        $user['integral']=$integral_array['integral'];
        //从数据库获取积分
        //$user['integral']=tel_get_integral($user['telphone']);

        //用户信息渲染到模板
        $this->view->assign('user', $user);
    }
    public function wechatlogin(){
        //基本设置
        $website=website();

        $wechat_user=Session::get('wechat_user');
        if(!isset($wechat_user)){
        	$Wechat_url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$website['appid']."&redirect_uri=".$website['web_url']."/index.php/index/user/index&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
          $this->redirect($Wechat_url);
          
        }
    }
}
?>